<?php
namespace app\lib\exception;

use Exception;
use think\exception\Handle;
use think\facade\Log;

/**
 * Class ExceptionHandler
 * @package app\lib\exception
 * TODO: 全局异常处理类 重写thinkPHP Exception Handler 类
 *  修改app.php exception_handle app\lib\exception\ExceptionHandler
 */

class ExceptionHandler extends Handle
{
    # http状态码
    private $code;
    # 提示信息
    private $message;
    # 错误状态码
    private $errorCode;

    # 需要返回当前客户端请求的url路径(可选)
    public function render(Exception $e)
    {
        # instanceof 判断是否是某某的子类
        if($e instanceof BaseException) {
            # 自定义异常类
            $this->code= $e->code;
            $this->message = $e->message;
            $this->errorCode = $e->errorCode;
        }else{
            # 开关 ->是否开启thinkPHP自带的异常类
            if (config('projectConfig.ExceptionSwitch'))
            {
                return parent::render($e);
            }else{
                $this->code = 500;
                # 具体错误信息
                $this->message = $e->getMessage();
                $this->errorCode = 5000;
                //服务器内部错误写入日志
                $this->recordErrorLog($e);
            }
        }
        $result = [
            'code'      =>  $this->code,
            'msg'       =>  $this->message,
            'errorCode' =>  $this->errorCode,
        ];
        return json($result,$this->code);
    }

    /**
     * @param Exception $e
     * 日志有问题
     */
    private function recordErrorLog(Exception $e)
    {
        Log::init([
            'type'  =>  'File',
            'level' =>  ['error'],
        ]);
        Log::record($e->getMessage(),'error');
        Log::save();
    }


}





















